package cn.ichiva.tools;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

/**
 * 读取classes path 下的配置文件 application.properties
 * 并将配置添加到System.setProperty
 * 支持按环境加载application-xxx.properties
 *
 * 可以通过 -Dproperties=xx 指定加载外部配置文件
 */
public class PropertiesUtil {

    public static void load() {
        Properties properties = new Properties();
        String propertiesPath = System.getProperty("properties");

        if(propertiesPath == null){
            loadResource(properties,"application.properties");

            String action = properties.getProperty("action");
            if(action != null && action.length() > 0){
                String fileName = String.format("application-%s.properties", action);
                loadResource(properties,fileName);
            }
        }else {
            loadFile(properties,propertiesPath);
        }

        Enumeration<?> enumeration = properties.propertyNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement().toString();
            String value = properties.getProperty(key);
            String property = System.getProperty(key);
            if(property == null){
                System.setProperty(key,value);
                System.out.printf("set %s=%s\n\r",key,value);
            }else {
                System.out.printf("find %s=%s\n\r",key,value);
            }
        }
    }

    private static void loadResource(Properties properties,String resource){
        System.out.println("load resource:" + resource);

        try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource)){
            properties.load(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void loadFile(Properties properties, String file){
        System.out.println("load file:" + file);

        try (InputStream in = new FileInputStream(file)){
            properties.load(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
